<?php

namespace Keio\StudyBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Keio\StudyBundle\Entity\Cauhoi;
use Keio\StudyBundle\Form\CauhoiType;
use Keio\StudyBundle\Entity\Cauhoitraloi;
use Keio\StudyBundle\Form\CauhoitraloiType;

/**
 * Cauhoi controller.
 *
 */
class CauhoiController extends Controller
{

    /**
     * Lists all Cauhoi entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('KeioStudyBundle:Cauhoi')->findAll();

        //set delete form cho mỗi element
        foreach ($entities as $element){
        	$deleteForm = $this->createDeleteForm($element->getId());
        	$element->setDelform($deleteForm->createView());
        }

        foreach ($entities as $entity){
        	$entity->setGoiyshort($em->getRepository('KeioStudyBundle:Blog')->getNbFirstChars($entity->getGoiy(),100));
        	$entity->setNoidungshort($em->getRepository('KeioStudyBundle:Blog')->getNbFirstChars($entity->getNoidung(),100));
        }

        return $this->render('KeioStudyBundle:Cauhoi:index.html.twig', array(
            'entities' => $entities,
        ));
    }
    /**
     * Creates a new Cauhoi entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity  = new Cauhoi();
        $cauhoi_loai = $request->get('cauhoi_loai');
        $entity->setLoai($cauhoi_loai);
        $form = $this->createForm(new CauhoiType(), $entity);
        $form->bind($request);

        $traloi = $request->get('form');


        if ($form->isValid()) {
        	$traloientities = $this->prepareProcessCreateUpdate(array(), $cauhoi_loai, $traloi, $entity);
            $em = $this->getDoctrine()->getManager();

            for ($k=0; $k<count($traloientities); $k++){
            	$em->persist($traloientities[$k]);
            }
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('keio_cauhoi'));
        }

        //failed form
        if ($cauhoi_loai==0){ //trac nghiem
        	return $this->redirect($this->generateUrl('keio_cauhoi_newtracnghiem'));
        }else{
        	return $this->redirect($this->generateUrl('keio_cauhoi_newtutraloi'));
        }
    }

    /**
     * Displays a form to create a new Cauhoi entity.
     *
     */
    public function newtutraloiAction()
    {
        $entity = new Cauhoi();
        $entity->setLoai(1);
        $form   = $this->createForm(new CauhoiType(), $entity);

        //form trả lời 1 là cho câu hỏi tự trả lời (ko phải trắc nghiệm)
        $form_traloi = $this->createFormBuilder()
        	->add('traloi', 'textarea', array('label'=>'Thiết kế câu trả lời'))
        	->getForm();

        return $this->render('KeioStudyBundle:Cauhoi:addcauhoi.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
            'form_traloi'=> $form_traloi->createView(),
        ));
    }

    public function newtracnghiemAction()
    {
        $entity = new Cauhoi();
        $entity->setLoai(0);
        $form   = $this->createForm(new CauhoiType(), $entity);

		//form trả lời 0 là cho Trắc nghiệm
        $form_traloi = $this->createFormBuilder()
        	->add('traloi1', 'textarea', array('label'=>'Câu trả lời 1'))
        	->add('traloi2', 'textarea', array('label'=>'Câu trả lời 2'))
        	->add('traloi3', 'textarea', array('label'=>'Câu trả lời 3'))
        	->add('traloi4', 'textarea', array('label'=>'Câu trả lời 4'))
        	->add('caudung', 'choice', array(
    				'label' => 'Câu đúng là:',
					'choices'   => array(
        			'1'   => 'Answer 1',
        			'2'   => 'Answer 2',
        			'3'   => 'Answer 3',
        			'4'   => 'Answer 4',
    				),
    			'multiple'  => false,
    			'expanded'    => true,
				))
        	->getForm();

        return $this->render('KeioStudyBundle:Cauhoi:addcauhoi.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
            'form_traloi'=> $form_traloi->createView(),
        ));
    }

    /**
     * Finds and displays a Cauhoi entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('KeioStudyBundle:Cauhoi')->find($id);

$traloi = $em->getRepository('KeioStudyBundle:Cauhoitraloi')->getTraloiByCauhoi($id);
        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Cauhoi entity.');
        }

        return $this->render('KeioStudyBundle:Cauhoi:show.html.twig', array(
            'entity'      => $entity,
            'traloi'      => $traloi,
        ));
    }

    /**
     * Displays a form to edit an existing Cauhoi entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('KeioStudyBundle:Cauhoi')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Cauhoi entity.');
        }

        $traloi = $em->getRepository('KeioStudyBundle:Cauhoitraloi')->getTraloiByCauhoi($id);
        $traloiid = array();
        for ($jj=0; $jj<count($traloi); $jj++){
        	$traloiid[]=$traloi[$jj]->getId();
        }
        if ($entity->getLoai()==0){
        	$defaultData = array(
								'traloi1' => $traloi[0]->getNoidung(),
								'traloi2' => $traloi[1]->getNoidung(),
								'traloi3' => $traloi[2]->getNoidung(),
								'traloi4' => $traloi[3]->getNoidung(),
								);
	        $caudung = 1; //init value
	        //tim cau tra loi dung
	        for ($j=0; $j<count($traloi); $j++){
	        	if ($traloi[$j]->getDungsai()==1){
	        		$caudung = $j+1;
	        	}
	        }
	        $defaultData['caudung'] = $caudung;
	        $form_traloi = $this->createFormBuilder($defaultData)
	        	->add('traloi1', 'textarea', array('label'=>'Câu trả lời 1'))
	        	->add('traloi2', 'textarea', array('label'=>'Câu trả lời 2'))
	        	->add('traloi3', 'textarea', array('label'=>'Câu trả lời 3'))
	        	->add('traloi4', 'textarea', array('label'=>'Câu trả lời 4'))
	        	->add('caudung', 'choice', array(
	    				'label' => 'Câu đúng là:',
						'choices'   => array(
	        			'1'   => 'Answer 1',
	        			'2'   => 'Answer 2',
	        			'3'   => 'Answer 3',
	        			'4'   => 'Answer 4',
	    				),
	    			'multiple'  => false,
	    			'expanded'    => true,
					))
	        	->getForm();
        }else{
        	$defaultData = array(
								'traloi' => $traloi[0]->getNoidung(),
								);
        	$form_traloi = $this->createFormBuilder($defaultData)
	        	->add('traloi', 'textarea', array('label'=>'Thiết kế câu trả lời'))
	        	->getForm();
        }


        $editForm = $this->createForm(new CauhoiType(), $entity);

        return $this->render('KeioStudyBundle:Cauhoi:modifycauhoi.html.twig', array(
            'entity'      => $entity,
            'form'        => $editForm->createView(),
            'form_traloi' => $form_traloi->createView(),
            'traloiid'    => $traloiid,
        ));
    }

    /**
     * Edits an existing Cauhoi entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('KeioStudyBundle:Cauhoi')->find($id);
        $traloiid = $request->get('traloiid');
        $traloi = $request->get('form');

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Cauhoi entity.');
        }

        $editForm = $this->createForm(new CauhoiType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {

        	$traloientities = $this->prepareProcessCreateUpdate($traloiid, $entity->getLoai(), $traloi, $entity);

            for ($k=0; $k<count($traloientities); $k++){
            	$em->persist($traloientities[$k]);
            }

            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('keio_cauhoi'));
        }

        return $this->redirect($this->generateUrl('keio_cauhoi_edit', array('id'=>$id)));
    }
    /**
     * Deletes a Cauhoi entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('KeioStudyBundle:Cauhoi')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Cauhoi entity.');
            }

            //check if contraint
			$checkconstraint = $em->getRepository('KeioStudyBundle:Cauhoi')->checkConstraintToDeleteCauhoi($id);
			if ($checkconstraint==1){ //having constraint
				$this->get('session')->getFlashBag()->add('msg', 'Delete failed because of constraint');
			}else{
				//delete traloi
				$traloi = $em->getRepository('KeioStudyBundle:Cauhoitraloi')->getTraloiByCauhoi($id);
				foreach ($traloi as $tl){
            		$em->remove($tl);
            	}

				$em->remove($entity);
            	$em->flush();
			}
        }

        return $this->redirect($this->generateUrl('keio_cauhoi'));
    }

    /**
     * Creates a form to delete a Cauhoi entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
    //prepare entities for create or update traloi
    private function prepareProcessCreateUpdate($traloiid, $cauhoi_loai, $traloi, $entity){
    	$em = $this->getDoctrine()->getManager();
        if ($cauhoi_loai==0){
	        if (count($traloiid)==0){ //new
				$traloi_entity1 = new Cauhoitraloi();
				$traloi_entity2 = new Cauhoitraloi();
				$traloi_entity3 = new Cauhoitraloi();
				$traloi_entity4 = new Cauhoitraloi();
	        }else{
	        	$traloi_entity1 = $em->getRepository('KeioStudyBundle:Cauhoitraloi')->find($traloiid[0]);
	        	$traloi_entity2 = $em->getRepository('KeioStudyBundle:Cauhoitraloi')->find($traloiid[1]);
	        	$traloi_entity3 = $em->getRepository('KeioStudyBundle:Cauhoitraloi')->find($traloiid[2]);
	        	$traloi_entity4 = $em->getRepository('KeioStudyBundle:Cauhoitraloi')->find($traloiid[3]);
	        }

	        //1
	        $traloi_entity1->setNoidung($traloi['traloi1']);
	        $traloi_entity1->setCauhoi($entity);
	        //init dungsai
	        $traloi_entity1->setDungsai(false);
	        $traloi_entity2->setDungsai(false);
	        $traloi_entity3->setDungsai(false);
	        $traloi_entity4->setDungsai(false);
	        if ($traloi['caudung'] ==1){
	        	$traloi_entity1->setDungsai(true);
	        }
	        if ($traloi['caudung'] ==2){
	        	$traloi_entity2->setDungsai(true);
	        }
	        if ($traloi['caudung'] ==3){
	        	$traloi_entity3->setDungsai(true);
	        }
	        if ($traloi['caudung'] ==4){
	        	$traloi_entity4->setDungsai(true);
	        }
	        //2
	        $traloi_entity2->setNoidung($traloi['traloi2']);
	        $traloi_entity2->setCauhoi($entity);

	        //3
	        $traloi_entity3->setNoidung($traloi['traloi3']);
	        $traloi_entity3->setCauhoi($entity);

	        //4
	        $traloi_entity4->setNoidung($traloi['traloi4']);
	        $traloi_entity4->setCauhoi($entity);

	        $traloientities = array(
	        						0=>$traloi_entity1,
	        						1=>$traloi_entity2,
	        						2=>$traloi_entity3,
	        						3=>$traloi_entity4,
	        						);
        }else{
        	if (count($traloiid)==0){ //new
				$traloi_entity = new Cauhoitraloi();
	        }else{
	        	$traloi_entity = $em->getRepository('KeioStudyBundle:Cauhoitraloi')->find($traloiid[0]);
	        }
	        $traloi_entity->setNoidung($traloi['traloi']);
	        $traloi_entity->setCauhoi($entity);
	        $traloi_entity->setDungsai(true);

	        $traloientities = array(
	        						0=>$traloi_entity,
	        						);
        }
        return $traloientities;
    }
}
